<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

    <title class="transl" data-fi="BirdWatch - Semanttinen havaintopalvelu" data-en="BirdWatch - Semantic Observation Service"></title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="" />
    <meta name="author" content="" />

    <link href="jquery-ui/css/ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet">
    <link href="jquery.mobile-1.1.0.min.css" rel="stylesheet">
    
    <!--<link rel="stylesheet" href="themes/pulsar.min.css" />-->
    <!--<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile.structure-1.1.1.min.css" />-->
    <!--<link rel="stylesheet" href="themes/Kerpo.min.css" />-->

    <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    
	<script src="parser.js"></script>
	<script src="jquery/jquery-1.7.2.min.js"></script>
	<script src="jquery-ui/js/jquery-ui-1.8.21.custom.min.js"></script>
	<script src="jquery.mobile-1.1.0.min.js"></script>
	<script src="https://www.google.com/jsapi"></script>
	<script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places&language=fi" type="text/javascript"></script>

	
	<style type="text/css">
	.rightAlign {
		text-align:right;
		}
    html { background-color: #F8F0F0; }
    
    .ui-btn-up-f, .ui-btn-hover-f, .ui-btn-down-f {
	  color: white;
	  font-weight: bold;
	  text-decoration: none; }

	.ui-btn-up-f {
	  border: 1px solid #711414;
	  background: #ab2525;
	  text-shadow: 0 -1px 1px #711414;
	  background-image: -moz-linear-gradient(top, #c44f4f, #ab2525);
	  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #c45e5e), color-stop(1, #9e3939));
	  -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#c44f4f', EndColorStr='#ab2525')"; }

	.ui-btn-hover-f {
	  border: 1px solid #6e0000;
	  background: #b54a4a;
	  text-shadow: 0 -1px 1px #690101;
	  background-image: -moz-linear-gradient(top, #d47272, #b54a4a);
	  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #d47272), color-stop(1, #b54a4a));
	  -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#d47272', EndColorStr='#b54a4a')"; }

	.ui-btn-down-f {
	  border: 1px solid #782323;
	  background: #c44f4f;
	  text-shadow: 0 -1px 1px #782323;
	  background-image: -moz-linear-gradient(top, #9e3939, #c44f4f);
	  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #9e3939), color-stop(1, #c44f4f));
	  -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#9e3939', EndColorStr='#c44f4f')"; }
	  
	.ui-btn-up-g, .ui-btn-hover-g, .ui-btn-down-g
	{
	color: white;
	font-weight: bold;
	text-decoration: none;
	}

	.ui-btn-up-g
	{
	border: 1px solid #397114;
	background: #5aab25;
	text-shadow: 0 -1px 1px #397114;
	background-image: -moz-linear-gradient(top, #7ec44f, #5aab25);
	background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #87c45e), color-stop(1, #619e39));
	-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#7ec44f', EndColorStr='#5aab25')";
	}

	.ui-btn-hover-g
	{
	border: 1px solid #2c6e00;
	background: #75b54a;
	text-shadow: 0 -1px 1px #2a6901;
	background-image: -moz-linear-gradient(top, #99d472, #75b54a);
	background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #99d472), color-stop(1, #75b54a));
	-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#99d472', EndColorStr='#75b54a')";
	}

	.ui-btn-down-g
	{
	border: 1px solid #457823;
	background: #7ec44f;
	text-shadow: 0 -1px 1px #457823;
	background-image: -moz-linear-gradient(top, #619e39, #7ec44f);
	background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #619e39), color-stop(1, #7ec44f));
	-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#619e39', EndColorStr='#7ec44f')";
	}

	.ui-btn-up-g, .ui-btn-hover-g, .ui-btn-down-g
	{
	color: white;
	font-weight: bold;
	text-decoration: none;
	}
	

.ui-icon{
	background-color:transparent;
	border: 0;
	margin: 0;
	padding: 0;
    width:0px;
    height:0px;
    -moz-border-radius: 0px;
    -webkit-border-radius:0px;
    border-radius:0px;
}
	
    </style>
    <style type='text/css'>
    <!--
        @media only screen and (min-width: 801px){
            .ui-page {
                width: 700px !important;
                margin: 0 auto !important;
                position: relative !important;
                border-right: 1px #CCCCCC solid !important;
                border-left: 1px #CCCCCC solid !important;
            }
        }
    -->
	</style>

  </head>

<body>
<div data-role="page" class="type-home">
    
    <div data-role="header" class="ui-bar-a ui-header" role="banner" data-theme="e">
    <img border="0" src="pulu.png" alt="lg" style="margin-left:10px; margin-right: 5px; margin-top: 3px; width: 30px; float:left;display:inline"/>
	<h1 style="text-align:left; margin-left:5px;" class="ui-title" tabindex="0" role="heading" aria-level="1">BirdWatch</h1>
	
	<div class="ui-btn-right">	
    <a id="langButton" data-mini="true" data-role="button" href="#" data-theme="e" data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span">
       <span class="ui-btn-text transl" data-fi="in English" data-en="suomeksi"></span>
    </a>
     <a data-mini="true" data-role="button" href="#" onClick="displayInfo();" data-theme="e" id="infoBut" data-corners="true" data-wrapperels="span">
     	<span class="ui-btn-text">?</span>
    </a>
</div>
</div>
    		
<div class="ui-body ui-body-b" id="mainDiv">
		<label for="taxonInput" class="transl" data-fi="Laji" data-en="Species"></label>
		<input id="taxonInput" class="ui-autocomplete-input" placeholder="Syötä havaittu laji"/>
		<label for="locationInput" class="transl" data-fi="Paikka" data-en="Location" ></label>
		<input id="locationInput" type="text" placeholder="Anna paikannimi tai osoite"/>
		<label for="datepicker" class="select transl" data-fi="Aika" data-en="Date"></label>
		<input name="date1" id="datepicker" type="text" />
		
		<!--<label for="select-choice-1" class="select transl" data-fi="Biotooppi" data-en="Biotope"></label>
		<select name="biotope" id="select-choice-1" data-mini="true" data-theme="c">
			<option value="-"></option>
			<option value="ulkosaaristo" class="transl" data-fi="ulkosaaristo" data-en="archipelago"></option>
			<option value="meri" class="transl" data-fi="meri" data-en="sea"></option>
			<option value="jarvitaijoki" class="transl" data-fi="järvi/joki" data-en="lake/river"></option>
			<option value="tunturi" class="transl" data-fi="tunturi" data-en="fell"></option>
			<option value="metsa" class="transl" data-fi="metsä" data-en="forest"></option>
			<option value="peltotaiavomaa" class="transl" data-fi="pelto/avomaa" data-en="field"></option>
			<option value="suo" class="transl" data-fi="suo" data-en="bog"></option>
			<option value="asutus" class="transl" data-fi="asutus" data-en="urban area"></option>
		</select>-->
		
		<div class="ui-grid-a">
			<div class="ui-block-a">
				<a data-inline="true" data-role="button" href="#" onClick="getResults();" data-theme="e">
					<span class="ui-btn-text transl" data-fi="Tarkista" data-en="Check"></span>
				</a>
			</div>

		</div>
		
		<!--Hae lajin tiedot</button>-->
		<p id="observationHolder"></p>
		<p id="speciesHolder"></p>
		<p id="resultHolder"></p>
		<p id="buttHolder"></p>
		<p id="infoHolder" class="transl" data-fi="" data-en=""></p>
		<p id="resultHolder2"></p>
	</div>
	
	<div class="ui-grid-a" style="visibility:hidden;" id="chartholder">

	<div data-shadow="false" data-role="collapsible" id="map">
   <h3 id="mapplot"><span class="transl" data-fi="Näytä kartalla" data-en="Show on map"></span></h3>
   <div id="mapHolder" style="width: 100%; height: 315px;"><img src="load.gif" alt="Loading ..."/></div>
	</div>
	
	<div data-shadow="false" data-role="collapsible" id="monthly">
   <h3 id="monthplot"><span class="transl" data-fi="Näytä havainnot kuukausittain" data-en="Show monthly stats"></h3>
   <div id="chart_div" style="width: 100%; height: 300px;"><img src="load.gif" alt="Loading ..."/></div>
	</div>
	
	<div data-shadow="false" data-role="collapsible" id="yearly">
   <h3 id="yearplot"><span class="transl" data-fi="Näytä havainnot vuosittain" data-en="Show yearly stats"></h3>
   <div id="chart_div2" style="width: 100%; height: 300px;"><img src="load.gif" alt="Loading ..."/></div>
	</div>
	</div>

	<script>
		var species_lat = [];
		var species_eng = [];
		var species_fin = [];
		var species_uri = [];

		var d = new Date();
		var year = d.getFullYear();
		var month = (d.getMonth() + 1);
		var date = d.getDate();

		var sparql_url = "http://mt08014.seco.hut.fi:9080/smetana/service/data/Tiira6/sparql?query=";

		var lang;

		var misIDs = [];
		var tax;
		var taxId;
		var taxName;

		var gjson;

		var range = 0.4;

		var width = $("#mainDiv").width();

		// Default language is finnish
		langFi(true);
		
		/** Get all taxon-names */
		$.ajax({
			url: "relay.php",
			data: {
				url: sparql_url + encodeURIComponent("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX taxmeon: <http://www.yso.fi/onto/taxmeon/> PREFIX taxonomic-ranks: <http://www.yso.fi/onto/taxonomic-ranks/>" +
					"SELECT ?label_fi ?label_en ?label_sci ?resource0 WHERE " + 
					"{ ?resource_fi rdf:type taxmeon:VernacularName . " +
					"?resource_en rdf:type taxmeon:VernacularName . " + 
					"?resource_fi taxmeon:inverse_of_hasVernacularName ?resource0 . " +
					"?resource_en taxmeon:inverse_of_hasVernacularName ?resource0 . " + 
					"?resource0 rdf:type taxonomic-ranks:Species . " + 
					"?resource_fi rdfs:label ?label_fi . " + 
					"?resource_en rdfs:label ?label_en . " +
					"OPTIONAL { ?resource0 taxmeon:completeTaxonName ?label_sci } . " + 
					"FILTER (lang(?label_fi) = \"fi\" && lang(?label_en) = \"en\") } " +
					"ORDER BY ?label_fi ") + "&output=json"
			},
			success: function (data) {
				var obj = $.parseJSON(data);

				for (x in obj.results.bindings) {
					species_fin.push( obj.results.bindings[ x ].label_fi.value );
					species_eng.push( obj.results.bindings[ x ].label_en.value );
					if (obj.results.bindings[ x ].hasOwnProperty('label_sci')) {
						species_lat.push( obj.results.bindings[ x ].label_sci.value.toLowerCase() );
					} else {
						species_lat.push( '' );
					}
					species_uri.push( obj.results.bindings[ x ].resource0.value );
				}
				// Change language to finnish again to update taxon names for species autocompletion
				langFi(false);
			},
			error: function () {
				console.log("Error getting taxon names");
			}
		});


		/** Datepicker code */
		$("#datepicker").datepicker({
			dateFormat: "dd.mm.yy"
		});
		$('div.ui-datepicker').css({
			fontSize: '12px'
		});

		if (date.toString().length == 1) date = "0" + date;
		if (month.toString().length == 1) month = "0" + month;

		/** Get the HTML DOM Object from jQuery Object and update with current date */
		$("#datepicker")[0].value = date + "." + month + "." + year;


		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(displayPosition, displayError, {
				enableHighAccuracy: true,
				timeout: 45000,
				maximumAge: 60000
			});
		}
		
		/*
		// Assign enter key for taxonInput-field
		$("#taxonInput").keyup(function (e) {
			if (e.keyCode == 13) {
				getResults();
			}
		});

		// Assign enter key for locationInput-field
		$("#locationInput").keyup(function (e) {
			if (e.keyCode == 13) {
				getResults();
			}
		});
		*/

		google.maps.event.addDomListener(window, 'load', googleAutocomplete);

		$('#monthly').bind('expand', function () {
			plotMonthlyObservations();
		}).bind('collapse', function () {
			// Collapsed;
		});

		$('#yearly').bind('expand', function () {
			plotOverAllObservations();
		}).bind('collapse', function () {
			// Collapsed
		});

		$('a#langButton').click(function () {
			resetResults();
			$('#taxonInput')[0].value = "";
			if (lang == "fi") langEn();
			else langFi(true);
		});


		google.load("visualization", "1", {
			packages: ["corechart"]
		});
		google.setOnLoadCallback(function () {
			//console.log("Google Chart API loaded ...")
		});





		/** Display help text */
		function displayInfo() {
			document.getElementById("speciesHolder").innerHTML = "";
			document.getElementById("resultHolder").innerHTML = "";
			document.getElementById("resultHolder2").innerHTML = "";
			document.getElementById("buttHolder").innerHTML = "";

			var r = document.getElementById("infoHolder");

			if ((r.innerHTML.length > 0) && ((r.innerHTML.substring(0, 7) == '<b>Ohje' && lang == 'fi') || (r.innerHTML.substring(0, 7) == '<b>Help' && lang == 'en'))) {
				r.innerHTML = "";
			} else {
				if (lang == 'fi') {
					r.innerHTML = "<b>Laji</b> - havaittu laji<br />";
					r.innerHTML = "<b>Laji</b> - havaittu laji<br />";
					r.innerHTML += "<b>Paikka</b> - havainnon paikka, koordinaatit tai teksti. Esim. \"Laajalahti, Espoo\"<br />";
					r.innerHTML += "<b>Aika</b> - havainnon aika<br />";
					r.innerHTML += "<p>Sovellus käyttää otosta Tiira-palvelun datasta vuosilta 2007-2011.<br /></p>";
					//r.innerHTML += "<b>Biotooppi</b> - biotooppi, jossa laji on havaittu<br />";
					r.innerHTML += '<p><a href="http://www.seco.tkk.fi/applications/birdwatch/">Lisätietoa sovelluksesta</a></p>';
				}
				if (lang == 'en') {
					r.innerHTML = "<b>Species</b> - observed species<br />";
					r.innerHTML += "<b>Location</b> - observation location in coordinates or text. Example: \"Laajalahti, Espoo\"<br />";
					r.innerHTML += "<b>Time</b> - observation time<br />";
					//r.innerHTML += "<b>Biotope</b> - observation biotope<br />";
					r.innerHTML += '<p><a href="http://www.seco.tkk.fi/applications/birdwatch/">More information about this application</a></p>';
				}
			}
		}

		/** Set language to finnish */
		function langFi( init_datepicker ) {
			$('.transl').each(function () {
				$(this).html($(this).data('fi'));
			});
			lang = 'fi';
			$("#taxonInput").autocomplete({
				minLength: 2,
				source: species_fin.concat([].concat(species_lat).sort())
			});

			//$('#select-choice-1')[ 0 ].value = '-';
			if (init_datepicker) {
				$.getScript("jquery-ui/js/jquery.ui.datepicker-fi.js", function () {});
			}

			$('#locationInput').attr('placeholder', 'Anna paikannimi tai osoite');
			$('#taxonInput').attr('placeholder', 'Syötä havaittu laji');

		}

		/** Set language to english */
		function langEn() {
			$('.transl').each(function () {
				$(this).html($(this).data('en'));
			});
			lang = 'en';
			$("#taxonInput").autocomplete({
				minLength: 2,
				source: [].concat(species_eng).sort().concat(species_lat.sort())
			});

			$.getScript("jquery-ui/js/jquery.ui.datepicker-en-GB.js", function () {});

			$('#locationInput').attr('placeholder', 'Write name of place or address');
			$('#taxonInput').attr('placeholder', 'Input observed species');
		}

		function changeTaxon(tax) {
			document.getElementById("taxonInput").value = tax
			getResults();
		}

		function resetResults() {
			$("#observationHolder").empty();
			$("#speciesHolder").empty();
			$("#resultHolder").empty();
			$("#resultHolder2").empty();
			$("#chartholder").css({
				"visibility": "hidden"
			});
			$("#monthly").trigger('collapse');
			$("#chart_div").empty();
			$("#yearly").trigger('collapse');
			$("#chart_div2").empty();
			$("#map").trigger('collapse');
			$("#mapHolder").empty();
			$("#buttHolder").empty();
		}


		function getMisIds( uri ) {

			/** create SPARQL-query for retrieving misidentifications */

			var sparqlQuery;

			sparqlQuery = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX hh: <http://www.hatikka.fi/havainnot/> PREFIX envirofi: <http://www.yso.fi/onto/envirofi/> PREFIX taxmeon: <http://www.yso.fi/onto/taxmeon/> " +
				"SELECT ?resource ?label ?common ?origcommon WHERE { " +
				"<" + uri + "> envirofi:hasCommonMisidentification ?misid . <" + uri + "> hh:general ?origcommon . ?resource hh:general ?common . " +
				"?resource envirofi:hasCommonMisidentification ?misid . " +
				"?resource taxmeon:hasVernacularName ?vern . ?vern rdfs:label ?label . " +
				"FILTER ( ?resource != <" + uri + "> ) . FILTER (lang(?label) = \"" + lang + "\") }";

			/** get propable misidentifications	*/
			$.ajax({
				url: "relay.php",
				//dataType: 'jsonp',
				data: {
					url: sparql_url + encodeURIComponent(sparqlQuery) + "&output=json"
				},
				success: function (data) {
					var obj = $.parseJSON(data);
					var r = document.getElementById("resultHolder");
					var misid_str = '';

					if (obj.results.bindings.length > 0) {
						misid_str += speciesLinks(tax, false, obj.results.bindings[0].origcommon.value === 'true', null) + '<br />';
						if (obj.results.bindings.length > 1) {
							if (lang == 'fi') 
								misid_str += "Varo sekoittamasta lajeihin: <br />";
							else if (lang == 'en') 
								misid_str += "Common misidentifications: <br />";
						} else {
							if (lang == 'fi') 
								misid_str += "Varo sekoittamasta lajiin: ";
							else if (lang == 'en') 
								misid_str += "Common misidentification: ";
						}
							for (x in obj.results.bindings) {
								misIDs.push(obj.results.bindings[x].resource.value);
								misid_str += speciesLinks(obj.results.bindings[x].label.value, true, obj.results.bindings[x].literal === 'true', obj.results.bindings[x].resource.value);
							}
					} else {
						misid_str += speciesLinks(tax, false, true, null) + '<br />';
						if (lang == 'fi') misid_str += "Ei helposti sekoitettavissa muihin lajeihin";
						else if (lang == 'en') misid_str += "No common misidentifications";
					}

					if (misid_str.length > 1) 
						r.innerHTML = misid_str;

				}
			});

		}


		/** Create 'Send' button */
		function createSendButton(googled, color) {
			var butt = '';

			butt += '<a data-inline="true" data-role="button" target="_new" href="tiira/index.php?laji=' + encodeURIComponent(tax) + '&pvm=' + encodeURIComponent(date + '.' + month + '.' + year) + '&lat=' + encodeURIComponent(userY) + '&lon=' + encodeURIComponent(userX);
			if (googled == true) butt += '&paikka=' + encodeURIComponent(locstr);
			butt += '"';

			if (lang == 'en') butt += ' title="Proceed to observation sending"';
			else butt += ' title="Siirry havainnon lähettämiseen"';
			butt += ' data-theme="e">';

			butt += '<span class="ui-btn-text transl" data-fi="Lähetä" data-en="Send">';
			if (lang == 'en') butt += 'Send';
			else butt += 'Lähetä';
			butt += '</span></a>';

			$('#buttHolder').html('<div id="innerButt" class="rightAlign"></div>');

			$('#innerButt').html(butt).trigger('create');
			//$('#innerButt').page();
		}


		/** Capitalize all separate words */
		function capitalizeWords(strSentence) {
			var s = strSentence.replace(/\s[a-z]/g, convertToUpper);
			s = s[0].toUpperCase() + s.substring(1);

			return s;

			function convertToUpper() {
				return arguments[0].toUpperCase();
			}
		}

		/** Capitalize first letter */
		function capitalizeFirst(strSentence) {
			return strSentence[0].toUpperCase() + strSentence.substring(1);
		}

		/** Generate misid-text */
		function speciesLinks(speciesName, bLink, bLuontoPortti, uri) {
			var thisStr = '';

			if (bLink) thisStr = '<a href href="#" onClick="changeTaxon(\'' + speciesName + '\');">';
			else thisStr = '<b id="speciesNameHolder">';

			if (lang == 'en') thisStr += capitalizeWords(speciesName);
			else thisStr += speciesName;

			if (bLink) thisStr += '</a>';
			else thisStr += '</b>';

			var speciesLP = speciesName.replace(/ä/g, "a").replace(/ö/g, "o")
			if (lang == 'fi') speciesLP = speciesLP.replace('isokuovi', 'kuovi');
			else {
				speciesLP = speciesLP.split('/')[0];
				speciesLP = speciesLP.replace('northern pintail', 'pintail').replace('common teal', 'teal');
				speciesLP = speciesLP.replace('barn swallow', 'swallow').replace('collared sand martin', 'sand martin');
				speciesLP = speciesLP.replace('eurasian ', '').replace('european ', '');
				speciesLP = speciesLP.replace('common linnet', 'linnet');
				speciesLP = speciesLP.replace(/ /g, '-');
			}

			var validTaxon = false;

			//console.log( speciesName );

			if (lang == 'en' && ($.inArray(speciesName, species_eng) != -1)) {
				validTaxon = true;
			}

			if (lang == 'fi' && ($.inArray(speciesName, species_fin) != -1)) {
				validTaxon = true;
			}

			if (validTaxon) {
				thisStr += " &nbsp;&nbsp; <a href=\"http://" + lang + ".wikipedia.org/wiki/" + capitalizeWords(speciesName.split('/')[0]) + "\" target=\"_blank\" title=\"Wikipedia\"><img src=\"w.ico\" /></a>";
				//if (lang == 'fi')

				if (bLuontoPortti) thisStr += " &nbsp;&nbsp; <a id=\"lp_" + speciesName + "\" href=\"http://www.luontoportti.com/suomi/" + lang + "/linnut/" + speciesLP + "\" target=\"_blank\" title=\"Luontoportti\"><img src=\"lp.ico\" /></a>";
				//$('#lp_' + speciesName).hide();

				if (lang == 'fi') thisStr += " &nbsp;&nbsp; <a href=\"http://atlas3.lintuatlas.fi/tulokset/laji/" + speciesName + "\" target=\"_blank\" title=\"Lintuatlas\"><img src=\"atlas.ico\" /></a>";

			}


			thisStr += "<br />";

			return thisStr;
		}


		function getObservationsMonthAgo(start_d, end_d) {
			//console.log("Getting observations month ago ...");

			var xlongmin = (parseFloat(window.userX) - range);
			var xlongmax = (parseFloat(window.userX) + range);

			var ylatmin = (parseFloat(window.userY) - range);
			var ylatmax = (parseFloat(window.userY) + range);

			sparqlQuery = "PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#> PREFIX fn: <http://www.w3.org/2005/xpath-functions#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX hh: <http://www.hatikka.fi/havainnot/> PREFIX envirofi: <http://www.yso.fi/onto/envirofi/> PREFIX taxmeon: <http://www.yso.fi/onto/taxmeon/> PREFIX owl-time: <http://www.w3.org/TR/2006/WD-owl-time-20060927/> " +
				"SELECT ?date ?lat ?long { ?ha hh:scientific_name <" + taxId + "> . ?ha rdf:type hh:Observation . ?ha owl-time:dayOfYear ?date . " +
				"?ha geo:lat ?lat . ?ha geo:long ?long . " +
				"FILTER ( xsd:float(?long) > " + xlongmin + " && xsd:float(?long) < " + xlongmax + " && xsd:float(?lat) > " + ylatmin + " && xsd:float(?lat) < " + ylatmax + ") . ";
			
			if (start_d < end_d) {
				sparqlQuery += "FILTER ((xsd:integer(?date) >= " + start_d + ") && (xsd:integer(?date) <= " + end_d + "))" +
								"}";
			} else {
				sparqlQuery += "FILTER ((xsd:integer(?date) >= " + start_d + ") || (xsd:integer(?date) <= " + end_d + "))" +
								"}";
			}
			
			$.ajax({
				url: "relay.php",
				data: {
					url: sparql_url + encodeURIComponent(sparqlQuery) + "&output=json"
				},
				success: function (data) {
					var obj = $.parseJSON(data);

					if (obj.results.bindings.length > 0) {
						if (lang == "fi") {
							$("#observationHolder").append("Alueella tehty " + obj.results.bindings.length + " havaintoa lajista " + tax + " tähän vuodenaikaan (+- 2 viikkoa)");
							//	$("#speciesNameHolder").append("havaintoa tähän vuodenaikaan (+-2 viikkoa)");
						} else {
							$("#observationHolder").append(obj.results.bindings.length + " " + tax + " sightings in the area in this time of year (+- 2 weeks)");
							//	$("#speciesNameHolder").append(" sightings in the area in this time of year (+- weeks)");						
						}

						var list = [];

						for (var i = 0; i < obj.results.bindings.length; i++) {
							list.push(obj.results.bindings[i]["lat"].value + "," + obj.results.bindings[i]["long"].value);
							//console.log(list[i]);
						}

					} else {

						if (lang == "fi") {
							$("#observationHolder").append("Alueella ei ole tehty yhtään havaintoa lajista " + tax + " tähän vuodenaikaan (+-2 viikkoa)");
							//	$("#speciesNameHolder").append("havaintoa tähän vuodenaikaan (+-2 viikkoa)");
						} else {
							$("#observationHolder").prepend("There has been no " + tax + " sightings in the area in this time of year (+- 2 weeks)");
							//	$("#speciesNameHolder").append(" sightings in the area in this time of year (+- weeks)");						
						}


					}

					//createSendButton();
					var width = $("#mainDiv").width();
					$("#mapHolder").html(getStaticMapHtml(parseFloat(window.userY), parseFloat(window.userX), width, list));
					$("#map").trigger('expand');


				}
			});

		}

		function updateHitStatus(odds) {

			if (lang == 'fi') {
				r.innerHTML = "Todennäköisyys lajin havaitsemiselle: " + (100 * odds).toFixed(1) + "%";
				r.innerHTML += "<br /><i>Koordinaatit: " + userY + ", " + userX + "</i>";
			} else {
				r.innerHTML = "Probability for observing species in the area: " + (100 * odds).toFixed(1) + "%";
				r.innerHTML += "<br /><i>Coordinates: " + userY + ", " + userX + "</i>";
			}

		}


		/** get propability for seeing the species here and now */
		function getProbs(taxId) {
			var param = "http://demo.seco.tkk.fi/json?" + 'lat=' + encodeURIComponent(userY) + '&lng=' + encodeURIComponent(userX) + '&d=' + selectedDate.getDOY() + '&uri=' + encodeURIComponent(taxId);
			if (biotope.length > 2) param += "&biotope=" + biotope;

			$.ajax({
				url: "relay.php",
				//dataType: 'jsonp',
				data: {
					url: param
				},
				error: function () {
					if (userX !== null && userY != null) {
						createSendButton(false, 'yellow');
					}
				},
				success: function (data) {

					try {
						var obj = data; //data;
					} catch (e) {
						var obj = [-1];
					}
					var hit = false;
					var coords;

					//console.log( obj[ 0 ] );

					if (userX !== null && userY != null) {
						if ((obj[0] >= 0) && (obj[0] < 2)) updateHitStatus(obj[0]);
						createSendButton(false, obj[1]);
					}

				}
			});
		}
		
				
		/** A bad species name was given */
		function badSpeciesName() {
			if (tax.length < 1) {
				if (lang == "en") $("#speciesHolder").append(tax + "Please write species name");
				else $("#speciesHolder").append(tax + "Kirjoita ensin lintulajin nimi");
			} else if (lang == "en") $("#speciesHolder").append(tax + " is not found from english bird names");
			else $("#speciesHolder").append(tax + " ei löydy suomalaisista lintujen nimistä");			
		}


		/** Get results from form */
		function getResults() {

			var locstr = $('#locationInput')[0].value;
			var locarr = locstr.split(' ');

			tax = document.getElementById("taxonInput").value.toLowerCase();

			/** Must have something in species name */
			if (tax == undefined || tax.length == 0) {
				badSpeciesName();
				return false;
			}

			/** Must have something in location */
			if (locstr == undefined || locstr.length == 0) {
				return false;
			}

			/** Parse format: Place (lat: yy, long: xx) */
			var latIndex = locstr.indexOf('(lat: ');
			var longIndex = locstr.indexOf(' long: ');

			if ((latIndex != -1) && (longIndex != -1)) {
				window.userX = parseFloat(locstr.substring(longIndex + 6, longIndex + 13));
				window.userY = parseFloat(locstr.substring(latIndex + 6, latIndex + 13));
			}
			else if ((locarr[0] == 'Latitude:') && (locarr[2] == 'Longitude:')) {
				window.userX = parseFloat(locarr[3]);
				window.userY = parseFloat(locarr[1]);
			} /*else {
				window.userX = null;
				window.userY = null;
			}*/

			/** If we don't get any coords, it's bye-bye */
			if (window.userX == null && window.userY == null) {
				return false;
			}

			resetResults();

			document.getElementById("infoHolder").innerHTML = "";

			if ($.inArray(tax, species_fin) != -1) {
				taxId = species_uri[ species_fin.indexOf( tax )];
			}
			else if ($.inArray(tax, species_lat) != -1) {
				taxId = species_uri[ species_lat.indexOf( tax )];
			}
			else if ($.inArray(tax, species_eng) != -1) {
				taxId = species_uri[ species_eng.indexOf( tax )];
			} else
			{
				badSpeciesName();
				return false;
			}
			
			var dateArr = document.getElementById("datepicker").value.split('.');

			date = dateArr[0];
			month = dateArr[1];
			year = '2012';
			selectedDate = new Date(year, parseInt(month) - 1, date);

			/** Calculate start and end dates for calculated observations */
			var startd = new Date(year, parseInt(month) - 1, parseInt(date) - 14);
			var endd = new Date(year, parseInt(month) - 1, parseInt(date) + 14);

			if (window.userX != null && window.userY != null) {

				getMisIds( taxId );
				getObservationsMonthAgo(startd.getDOY(), endd.getDOY());
				createSendButton(false);

				$("#chartholder").css({
					"visibility": "visible"
				});
			}
		}


		function plotOverAllObservations() {
			//console.log("Gettin overall observations ...");

			var xlongmin = (parseFloat(window.userX) - range);
			var xlongmax = (parseFloat(window.userX) + range);

			var ylatmin = (parseFloat(window.userY) - range);
			var ylatmax = (parseFloat(window.userY) + range);

			sparqlQuery = "PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#> PREFIX fn: <http://www.w3.org/2005/xpath-functions#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX hh: <http://www.hatikka.fi/havainnot/> PREFIX envirofi: <http://www.yso.fi/onto/envirofi/> PREFIX taxmeon: <http://www.yso.fi/onto/taxmeon/> " +
				"SELECT xsd:string(?year) (COUNT(?date) AS ?Lkm) { ?ha hh:scientific_name <" + taxId + "> . ?ha rdf:type hh:Observation . ?ha hh:date_collected ?date . " +
				"?ha geo:lat ?lat . ?ha geo:long ?long . " +
				"FILTER ( xsd:float(?long) > " + xlongmin + " && xsd:float(?long) < " + xlongmax + " && xsd:float(?lat) > " + ylatmin + " && xsd:float(?lat) < " + ylatmax + ") . " +
				"} GROUP BY (year(?date) AS ?year) ORDER BY ASC(?year)";

			//console.log(sparqlQuery);

			$.ajax({
				url: "relay.php",
				//dataType: 'jsonp',
				data: {
					url: sparql_url + encodeURIComponent(sparqlQuery) + "&output=json"
				},
				success: function (data) {
					var obj = $.parseJSON(data);



					//console.log("json:"); 
					//console.log(data);

					if (obj.results.bindings.length > 1) {

						gjson = sgvizler.parser.SparqlJSON2GoogleJSON(obj);
						//console.log("gjson:"); 
						//console.log(gjson);


						var options;

						if (lang == 'en') {
							options = {
								annotation: {
									2: {
										style: 'line'
									}
								},
								title: 'All yearly' + tax + ' observations from the area (2007-2011)',
								width: width,
								curveType: "function",
								hAxis: {
									title: 'Year',
									showTextEvery: 1
								},
								vAxis: {
									viewWindowMode: "explicit",
									viewWindow: {
										min: 0
									}
								}
							};
						} else {
							options = {
								annotation: {
									2: {
										style: 'line'
									}
								},
								title: 'Alueen kaikki vuosittaiset havainnot lajista ' + tax + ' (2007-2011)',
								width: width,
								curveType: "function",
								hAxis: {
									title: 'Vuosi',
									showTextEvery: 1
								},
								vAxis: {
									viewWindowMode: "explicit",
									viewWindow: {
										min: 0
									}
								}
							};

						}

						var data = new google.visualization.DataTable(gjson);

						//console.log(data.toJSON());


						var chart = new google.visualization.LineChart(document.getElementById('chart_div2'));
						chart.draw(data, options);

					} else {
						// TODO This isnt working why ?
						$('#chartdiv2').html("<p>Ei yhtään havaintoja</p>");

					}

				}

			});



		}

		function plotMonthlyObservations() {
			//console.log("Getting monthly observations ...");

			var sparqlQuery;

			var xlongmin = (parseFloat(window.userX) - range);
			var xlongmax = (parseFloat(window.userX) + range);

			var ylatmin = (parseFloat(window.userY) - range);
			var ylatmax = (parseFloat(window.userY) + range);

			sparqlQuery = "PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#> PREFIX fn: <http://www.w3.org/2005/xpath-functions#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX hh: <http://www.hatikka.fi/havainnot/> PREFIX envirofi: <http://www.yso.fi/onto/envirofi/> PREFIX taxmeon: <http://www.yso.fi/onto/taxmeon/> " +
				"SELECT xsd:string(?mon) (COUNT(?ha) AS ?Lkm) { ?ha hh:scientific_name <" + taxId + "> . ?ha rdf:type hh:Observation . ?ha hh:date_collected ?date . " +
				"?ha geo:lat ?lat . ?ha geo:long ?long . " +
				"FILTER ( xsd:float(?long) > " + xlongmin + " && xsd:float(?long) < " + xlongmax + " && xsd:float(?lat) > " + ylatmin + " && xsd:float(?lat) < " + ylatmax + ") . " +
				"} GROUP BY (month(?date) AS ?mon) ORDER BY ASC(?mon)";


			//console.log(sparqlQuery);

			$.ajax({
				url: "relay.php",
				//dataType: 'jsonp',
				data: {
					url: sparql_url + encodeURIComponent(sparqlQuery) + "&output=json"
				},
				success: function (data) {
					var obj = $.parseJSON(data);

					//	console.log("json:"); 
					//console.log(data);

					if (obj.results.bindings.length > 1) {

						gjson = sgvizler.parser.SparqlJSON2GoogleJSON(obj);
						//console.log("gjson:"); 
						//console.log(gjson);


						var options;

						if (lang == 'en') {
							options = {
								annotation: {
									2: {
										style: 'line'
									}
								},
								title: 'All monthly ' + tax + '-observations from the area (2007-2011)',
								width: width,
								height: width * 2,
								curveType: "function",
								hAxis: {
									title: 'Month',
									showTextEvery: 1
								},
								vAxis: {
									viewWindowMode: "explicit",
									viewWindow: {
										min: 0
									}
								}
							};
						} else {
							options = {
								annotation: {
									2: {
										style: 'line'
									}
								},
								title: 'Alueen ' + tax + '-havaintojen yhteismäärät kuukausittain (2007-2011)',
								width: width,
								height: width * 2,
								curveType: "function",
								hAxis: {
									title: 'Kuukausi',
									showTextEvery: 1
								},
								vAxis: {
									viewWindowMode: "explicit",
									viewWindow: {
										min: 0
									}
								}
							};

						}

						var data = new google.visualization.DataTable(gjson);


						data.addColumn({
							type: 'string',
							role: 'annotation'
						});

						// If there is no obervation data on some month add 0 

						var months;

						if (lang == "en") months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
						else months = ["Tam", "Hel", "Maa", "Huh", "Tou", "Kes", "Hei", "Elo", "Syys", "Lok", "Mar", "Jou"];

						for (var i = 0; i < data.getNumberOfRows(); i++) {
							var row = data.getValue(i, 0);

							pMonth = parseInt(row, 10);

							if (month == (i + 1)) {
								data.setValue(i, 2, (lang == "fi" ? "Ilmoittamasi havainto" : "Your observation"));
							}
							// IF some month is missing add new row
							if (i + 1 != pMonth) {
								data.insertRows(i, 1);
								data.setValue(i, 0, months[i]);
								data.setValue(i, 1, 0);
							} else data.setValue(i, 0, months[i]);

						}

						// IF months missing from the end of the table
						while (data.getNumberOfRows() < 12) {
							data.addRow([months[data.getNumberOfRows()], 0, null]);
						}

						//console.log(data.toJSON());


						var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
						chart.draw(data, options);

					} else {
						// TODO This isnt working why ?
						//document.getElementById('chart_div').value="<p>Ei yhtään havaintoja</p>";

					}


				}

			});

		}


		/** Geolocation stuff */

		function getStaticMapHtml(x, y, w, list) {

			html = '<img src="http://maps.google.com/maps/api/staticmap?center=' + x + ',' + y + '&markers=' + x + ',' + y + '&zoom=09&size=' + w + 'x320&maptype=terrain&sensor=false';

			if (list != null && list.length > 0) {
				for (var i = 0; i < list.length && html.length < 1800; i++)
				html += "&markers=size:tiny|label:S|" + list[i];
			}

			html += "&key=ABQIAAAAOVuTVW1aChPiS8ukar-AChRkY9KrTsc54SNfat8hJ7dc0OtNkRRuDC5nOgkBT53gdVJJH7oIXf0z-g"
			html += "\"/>";

			return html;

		}

		function displayPosition(position) {
			var lat = position.coords.latitude.toFixed(4);
			var lon = position.coords.longitude.toFixed(4);
			$('#locationInput')[0].value = 'Latitude: ' + lat + ", Longitude: " + lon;
		}

		function displayError() {
			//  $('#locationInput').attr('placeholder','Write placename (Town, placename) or address');
			if ($('#locationInput')[0].value.length == 0) {
				if (lang == 'fi') 
					$('#locationInput')[0].value = 'Paikan hakeminen epäonnistui';
				else 
					$('#locationInput')[0].value = 'Unable to get current location';
			}
		}

		function googleAutocomplete() {

			var options = {
				types: ['geocode'],
				componentRestrictions: {
					country: "fi"
				}
			};

			var input = document.getElementById('locationInput');
			var autocomplete = new google.maps.places.Autocomplete(input, options);

			google.maps.event.addListener(autocomplete, 'place_changed', function () {

				var place = autocomplete.getPlace();
				if (!place.geometry) {
					// Can this happen? 
				} else {
					window.userX = place.geometry.location.lng().toFixed(4);
					window.userY = place.geometry.location.lat().toFixed(4);
					input.value = input.value + " (lat: " + window.userY + ", long: " + window.userX + ")";
				}
			});
		}

		Date.prototype.getDOY = function () {
			var onejan = new Date(this.getFullYear(), 0, 1);
			return Math.ceil((this - onejan) / 86400000) + 1;
		}

	</script>
</div>		
</body>
</html>
